package dao.mysql.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import dao.IProductParamsDao;

public class ProductParamsDao implements IProductParamsDao {

	final String INSERT_PARAM = "insert into product_param (productId, paramKey, paramValue) values (?,?,?);";

	final String SELECT_ALL_PARAMS = "select * from product_param";

	@Override
	public void insertAll(int prodId, Map<String, Object> params) {
		// TODO Auto-generated method stub
		try {
			Connection conn = Configuration.getConnection();

			if (prodId <= 0)
				return;

			for (String key : params.keySet()) {
				PreparedStatement stmt = conn.prepareStatement(INSERT_PARAM);
				stmt.setInt(1, prodId);
				stmt.setString(2, key);
				stmt.setString(3, (String) params.get(key));

				stmt.executeUpdate();
				stmt.close();
			}

			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void selectAll(Map<Integer, Map<String, String>> params) {
		try {
			Connection conn = Configuration.getConnection();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(SELECT_ALL_PARAMS);

			while (rs.next()) {
				int id = rs.getInt("productId");
				String key = rs.getString("paramKey");
				String value = rs.getString("paramValue");

				if (!params.containsKey(id))
					params.put(id, new HashMap<String, String>());
				params.get(id).put(key, value);
			}

			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
